package com.mc.fastkit.dialog.animator

import android.animation.ValueAnimator
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.core.animation.doOnEnd
import androidx.core.graphics.drawable.toDrawable
import androidx.core.view.drawToBitmap
import androidx.interpolator.view.animation.FastOutSlowInInterpolator
import com.mc.fastkit.ext.activity
import com.mc.fastkit.ext.clip
import com.mc.fastkit.ext.renderScriptBlur

/**
 * 背景高斯模糊
 * @author: MasterChan
 * @date: 2024-02-19 11:03
 */
class BlurAnimator(
    private val scale: Float = 0.5f,
    private val radius: Float = 25f,
    private val includeNavigationBar: Boolean = false
) : BgAnimator() {

    private var blurImage: Drawable? = null

    override fun init() {
        val decorView = target!!.context.activity!!.window!!.decorView
        var blurBitmap = decorView.drawToBitmap().renderScriptBlur(scale, radius)
        if (!includeNavigationBar) {
            decorView.findViewById<View>(android.R.id.navigationBarBackground)?.let {
                blurBitmap = blurBitmap.clip(
                    Rect(0, 0, decorView.width, decorView.height - it.height)
                )
            }
        }
        blurImage = blurBitmap.toDrawable(target!!.resources)
        blurImage!!.colorFilter = PorterDuffColorFilter(startColor, PorterDuff.Mode.CLEAR)
        target!!.background = blurImage
    }

    override fun show(onEnd: (() -> Unit)?) {
        val animator = ValueAnimator.ofObject(evaluator, startColor, bgColor)
        animator.addUpdateListener {
            blurImage!!.colorFilter = PorterDuffColorFilter(
                it.animatedValue as Int, PorterDuff.Mode.SRC_OVER
            )
            target!!.background = blurImage
        }
        animator.interpolator = FastOutSlowInInterpolator()
        onEnd?.let { callback -> animator.doOnEnd { callback.invoke() } }
        animator.setDuration(duration).start()
    }

    override fun dismiss(onEnd: (() -> Unit)?) {
        val animator = ValueAnimator.ofObject(evaluator, bgColor, startColor)
        animator.addUpdateListener {
            val value = it.animatedValue as Int
            if (value <= 0) {
                blurImage!!.colorFilter = PorterDuffColorFilter(startColor, PorterDuff.Mode.CLEAR)
            } else {
                blurImage!!.colorFilter = PorterDuffColorFilter(value, PorterDuff.Mode.SRC_OVER)
            }
            target!!.background = blurImage
        }
        animator.interpolator = FastOutSlowInInterpolator()
        onEnd?.let { callback -> animator.doOnEnd { callback.invoke() } }
        animator.setDuration(duration).start()
    }
}